//
// Created by cen on 2025/8/16.
//

#include <iostream>
#include <memory>

using namespace std;


namespace SharedPtr {
    template<class T>
    class shared_ptr {
    public:
        shared_ptr(T *_ptr) : ptr(_ptr), cnt(new int(1)) {}

        T& operator*() {
            return *ptr;
        };

        T* &operator->() {
            return ptr;
        }

        shared_ptr& operator=(const shared_ptr<T> &sptr) {
            if(ptr != sptr.ptr) {   // 不同空间
                if(--(*cnt) == 0) {
                    delete ptr;
                    delete cnt;
                }
                ptr = sptr.ptr;
                cnt = sptr.cnt;
                (*cnt)++;
            }
            return *this;
        }

        ~shared_ptr() {
            if(--(*cnt) == 0) {
                if(ptr) {
                    delete ptr;
                    ptr = nullptr;
                }
                delete cnt;
                cnt = nullptr;
            }
        }

    private:
        T *ptr;
        // 记录有多少个对象共享资源，最后一个进行释放
        int *cnt;
    };
};

int main() {
    int *ptr;
    SharedPtr::shared_ptr<int> sharedPtr1(ptr);
    SharedPtr::shared_ptr<int> sharedPtr2(new int);

    sharedPtr1 = sharedPtr2;

    return 0;
}